import logging
import pymysql
from django.http import JsonResponse

from comment.comservice import add_filter
from comment.comviews import com_views, success_response, err_response, format_response
from utils.dbutils import PymysqlUtil, DB_Config, MysqlTools
from utils.formatutils import get_params
from utils.pageutils import paging_simple
from .sqlmap import *

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


def all_train_classify(params):
    """
    查询所有绩效分类
    :param params:
    :return:
    """
    dict = {
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    sql = TrainSqlMap.FIND_ALL_CLASSIFY.format(**params)
    result_all = mysql_tools.select_all(sql)
    return success_response(result_all)


def my_read(params):  # 我的已读
    dict = {
        "user_id": "user_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str_read": "query_str"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # if not params["user_id"]:
    #     return err_response(210)
    sql = add_filter(TrainSqlMap.my_read, params, ["query_str_read"], **TrainSqlMap.FILTER_PARAMS)
    sql += " order by t.read_time desc"
    sql = sql.format(**params)
    result = mysql_tools.select_all(sql)
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        if res["read_time"]:
            res["read_time"] = str(res["read_time"], encoding="utf-8")
            res["read_time"] = res["read_time"].split(".")[0]
    return success_response(result)


def train_check(params):  # 查看
    dict = {
        "id": "id",
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # if not params["id"]:
    #     return err_response(210)
    sql_article = TrainSqlMap.article.format(**params)
    result = mysql_tools.select_one(sql_article)
    if not result:
        return success_response([])
    result["create_time"] = str(result["create_time"], encoding="utf-8")
    num = mysql_tools.select_one(TrainSqlMap.FILE_NUM.format(**params))
    result["file_num"] = num["file_num"]
    sql_FILE = TrainSqlMap.FILE.format(**params)
    file = mysql_tools.select_all(sql_FILE)
    result["attach_list"] = file

    # 更新record表
    sql_insert = TrainSqlMap.INSERT_RECORD.format(**params)
    mysql_tools.execute_sql(sql_insert, commit=True)

    # 更新train阅读次数
    sql_update = TrainSqlMap.UPDATE_TRAIN.format(**params)
    mysql_tools.execute_sql(sql_update, commit=True)
    if result.get("create_time"):
        result["create_time"] = result.get("create_time").split(".")[0]
    return success_response(result)


def train_list(params):
    dict = {
        "user_id": "user_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str": "query_str",
        "classify": "status_id"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # if not params["user_id"]:
    #     return err_response(210)
    sql = add_filter(TrainSqlMap.TRAIN_LIST, params, ["query_str", "classify"], **TrainSqlMap.FILTER_PARAMS)
    sql += " order by t1.create_time desc"
    result = mysql_tools.select_all(sql.format(**params))
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        res["is_public"] = int.from_bytes(res["is_public"], byteorder='big')
        if res["is_public"] == 1:
            res["is_public"] = "发布"
        else:
            res["is_public"] = "未发布"
        res["create_time"] = str(res["create_time"], encoding="utf-8")
        num = mysql_tools.select_one(TrainSqlMap.FILE_NUM.format(**res))
        res["file_num"] = num["file_num"]
        if res.get("create_time"):
            res["create_time"] = res.get("create_time").split(".")[0]
    return success_response(result)


@format_response
def index(request):
    return com_views(request, {
        "my_read": my_read,
        # "classify_inquire": classify_inquire,
        "train_check": train_check,
        "train_list": train_list
    })
